package org.dromara.app.controller.app;

import jakarta.validation.Valid;
import jakarta.validation.constraints.*;
import lombok.RequiredArgsConstructor;
import org.dromara.app.domain.bo.AppVersionBo;
import org.dromara.app.domain.vo.AppVersionVo;
import org.dromara.app.service.AppVersionService;
import org.dromara.common.core.domain.R;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.log.annotation.Log;
import org.dromara.common.log.enums.BusinessType;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.web.core.BaseController;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * App端版本管理
 *
 * @author ruoyi
 */
@Tag(name = "App端版本管理", description = "App端版本管理相关接口")
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/app/version")
public class AppVersionController extends BaseController {

    private final AppVersionService appVersionService;

    /**
     * 查询App版本信息列表
     */
    @Operation(summary = "查询版本列表", description = "查询App版本信息列表")
    @GetMapping("/list")
    public TableDataInfo<AppVersionVo> list(@Parameter(description = "查询条件") @Valid AppVersionBo bo, 
                                            @Parameter(description = "分页参数") @Valid PageQuery pageQuery) {
        return appVersionService.queryPageList(bo, pageQuery);
    }

    /**
     * 获取App版本信息详细信息
     */
    @Operation(summary = "获取版本详情", description = "获取App版本信息详细信息")
    @GetMapping("/{versionId}")
    public R<AppVersionVo> getInfo(@Parameter(description = "版本ID", required = true) 
                                   @PathVariable @NotNull(message = "版本ID不能为空") @Positive(message = "版本ID必须为正数") Long versionId) {
        return R.ok(appVersionService.queryById(versionId));
    }

    /**
     * 检查版本更新
     */
    @Operation(summary = "检查版本更新", description = "检查是否有新版本可用")
    @GetMapping("/checkUpdate")
    public R<Map<String, Object>> checkUpdate(@Parameter(description = "平台类型(android/ios/web)", required = true) 
                                             @RequestParam @NotBlank(message = "平台类型不能为空") @Pattern(regexp = "^(android|ios|web)$", message = "平台类型只能为android、ios或web") String platform, 
                                             @Parameter(description = "当前版本号", required = true) 
                                             @RequestParam @NotNull(message = "当前版本号不能为空") @Positive(message = "当前版本号必须为正数") Integer currentVersionCode) {
        if (StringUtils.isBlank(platform)) {
            return R.fail("平台类型不能为空");
        }
        if (currentVersionCode == null || currentVersionCode <= 0) {
            return R.fail("当前版本号无效");
        }
        
        AppVersionVo updateInfo = appVersionService.getUpdateInfo(platform, currentVersionCode);
        Map<String, Object> result = new HashMap<>();
        
        if (updateInfo != null) {
            result.put("hasUpdate", true);
            result.put("versionInfo", updateInfo);
            result.put("isForce", "1".equals(updateInfo.getIsForce()));
            result.put("needUpdate", true);
        } else {
            result.put("hasUpdate", false);
            result.put("needUpdate", false);
            result.put("isForce", false);
            result.put("message", "当前已是最新版本");
        }
        
        return R.ok(result);
    }

    /**
     * 获取最新版本信息
     */
    @Operation(summary = "获取最新版本", description = "获取指定平台的最新版本信息")
    @GetMapping("/latest")
    public R<AppVersionVo> getLatestVersion(@Parameter(description = "平台类型(android/ios/web)", required = true) 
                                           @RequestParam @NotBlank(message = "平台类型不能为空") @Pattern(regexp = "^(android|ios|web)$", message = "平台类型只能为android、ios或web") String platform) {
        if (StringUtils.isBlank(platform)) {
            return R.fail("平台类型不能为空");
        }
        
        AppVersionVo latestVersion = appVersionService.getLatestVersion(platform);
        if (latestVersion == null) {
            return R.fail("未找到该平台的版本信息");
        }
        
        return R.ok(latestVersion);
    }

    /**
     * 获取版本历史记录
     */
    @Operation(summary = "获取版本历史", description = "获取指定平台的版本历史记录")
    @GetMapping("/history")
    public R<List<AppVersionVo>> getVersionHistory(@Parameter(description = "平台类型(android/ios/web)", required = true) 
                                                  @RequestParam @NotBlank(message = "平台类型不能为空") @Pattern(regexp = "^(android|ios|web)$", message = "平台类型只能为android、ios或web") String platform,
                                                  @Parameter(description = "返回数量限制") 
                                                  @RequestParam(defaultValue = "10") @Min(value = 1, message = "限制数量必须大于0") @Max(value = 100, message = "限制数量不能超过100") Integer limit) {
        if (StringUtils.isBlank(platform)) {
            return R.fail("平台类型不能为空");
        }
        
        List<AppVersionVo> versionHistory = appVersionService.getVersionHistory(platform, limit);
        return R.ok(versionHistory);
    }

    /**
     * 检查是否强制更新
     */
    @Operation(summary = "检查强制更新", description = "检查当前版本是否需要强制更新")
    @GetMapping("/checkForceUpdate")
    public R<Map<String, Object>> checkForceUpdate(@Parameter(description = "平台类型(android/ios/web)", required = true) 
                                                  @RequestParam @NotBlank(message = "平台类型不能为空") @Pattern(regexp = "^(android|ios|web)$", message = "平台类型只能为android、ios或web") String platform,
                                                  @Parameter(description = "当前版本号", required = true) 
                                                  @RequestParam @NotNull(message = "当前版本号不能为空") @Positive(message = "当前版本号必须为正数") Integer currentVersionCode) {
        if (StringUtils.isBlank(platform)) {
            return R.fail("平台类型不能为空");
        }
        if (currentVersionCode == null || currentVersionCode <= 0) {
            return R.fail("当前版本号无效");
        }
        
        Boolean forceUpdate = appVersionService.checkForceUpdate(platform, currentVersionCode);
        Map<String, Object> result = new HashMap<>();
        result.put("forceUpdate", forceUpdate);
        
        if (forceUpdate) {
            AppVersionVo updateInfo = appVersionService.getUpdateInfo(platform, currentVersionCode);
            result.put("versionInfo", updateInfo);
        }
        
        return R.ok(result);
    }

    /**
     * 获取更新信息
     */
    @Operation(summary = "获取更新信息", description = "获取详细的版本更新信息")
    @GetMapping("/updateInfo")
    public R<Map<String, Object>> getUpdateInfo(@Parameter(description = "平台类型(android/ios/web)", required = true) 
                                               @RequestParam @NotBlank(message = "平台类型不能为空") @Pattern(regexp = "^(android|ios|web)$", message = "平台类型只能为android、ios或web") String platform,
                                               @Parameter(description = "当前版本号", required = true) 
                                               @RequestParam @NotNull(message = "当前版本号不能为空") @Positive(message = "当前版本号必须为正数") Integer currentVersionCode) {
        if (StringUtils.isBlank(platform)) {
            return R.fail("平台类型不能为空");
        }
        if (currentVersionCode == null || currentVersionCode <= 0) {
            return R.fail("当前版本号无效");
        }
        
        AppVersionVo updateInfo = appVersionService.getUpdateInfo(platform, currentVersionCode);
        Map<String, Object> result = new HashMap<>();
        
        if (updateInfo != null) {
            result.put("hasUpdate", true);
            result.put("versionCode", updateInfo.getVersionCode());
            result.put("versionName", updateInfo.getVersionName());
            result.put("updateContent", updateInfo.getUpdateContent());
            result.put("downloadUrl", updateInfo.getDownloadUrl());
            result.put("isForce", "1".equals(updateInfo.getIsForce()));
            result.put("platform", updateInfo.getPlatform());
            result.put("createTime", updateInfo.getCreateTime());
        } else {
            result.put("hasUpdate", false);
            result.put("message", "当前已是最新版本");
        }
        
        return R.ok(result);
    }

    /**
     * 版本比较
     */
    @Operation(summary = "版本比较", description = "比较两个版本之间的差异")
    @GetMapping("/compare")
    public R<Map<String, Object>> compareVersion(@Parameter(description = "平台类型(android/ios/web)", required = true) 
                                                @RequestParam @NotBlank(message = "平台类型不能为空") @Pattern(regexp = "^(android|ios|web)$", message = "平台类型只能为android、ios或web") String platform,
                                                @Parameter(description = "当前版本号", required = true) 
                                                @RequestParam @NotNull(message = "当前版本号不能为空") @Positive(message = "当前版本号必须为正数") Integer currentVersionCode,
                                                @Parameter(description = "目标版本号", required = true) 
                                                @RequestParam @NotNull(message = "目标版本号不能为空") @Positive(message = "目标版本号必须为正数") Integer targetVersionCode) {
        if (StringUtils.isBlank(platform)) {
            return R.fail("平台类型不能为空");
        }
        if (currentVersionCode == null || targetVersionCode == null) {
            return R.fail("版本号不能为空");
        }
        
        Map<String, Object> result = new HashMap<>();
        result.put("platform", platform);
        result.put("currentVersionCode", currentVersionCode);
        result.put("targetVersionCode", targetVersionCode);
        
        if (targetVersionCode > currentVersionCode) {
            result.put("needUpdate", true);
            result.put("updateType", "upgrade");
        } else if (targetVersionCode < currentVersionCode) {
            result.put("needUpdate", false);
            result.put("updateType", "downgrade");
        } else {
            result.put("needUpdate", false);
            result.put("updateType", "same");
        }
        
        return R.ok(result);
    }

    /**
     * 记录版本下载
     */
    @Operation(summary = "记录版本下载", description = "记录用户下载版本的行为")
    @Log(title = "App版本下载", businessType = BusinessType.OTHER)
    @PostMapping("/download/{versionId}")
    public R<Void> recordDownload(@Parameter(description = "版本ID", required = true) 
                                  @PathVariable @NotNull(message = "版本ID不能为空") @Positive(message = "版本ID必须为正数") Long versionId) {
        // 这里可以记录下载统计等信息
        return R.ok();
    }

    /**
     * 记录版本安装
     */
    @Operation(summary = "记录版本安装", description = "记录用户安装版本的行为")
    @Log(title = "App版本安装", businessType = BusinessType.OTHER)
    @PostMapping("/install/{versionId}")
    public R<Void> recordInstall(@Parameter(description = "版本ID", required = true) 
                                 @PathVariable @NotNull(message = "版本ID不能为空") @Positive(message = "版本ID必须为正数") Long versionId) {
        // 这里可以记录安装统计等信息
        return R.ok();
    }

}